package com.estronger.shopmanage.ui.send;

import android.app.Activity;
import android.content.Intent;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.AbnormalType;
import com.estronger.shopmanage.bean.B12Measure;
import com.estronger.shopmanage.bean.B21SendDetail;
import com.estronger.shopmanage.bean.B22SendContent;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.bean.BeanImage;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.order.bean.OrderAttributeBean;
import com.estronger.shopmanage.ui.personal.PersonalActivity;
import com.estronger.shopmanage.view.AbnormalDeclareView;
import com.estronger.shopmanage.view.AddPhotosView;
import com.estronger.shopmanage.view.AddVideoView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.soonfor.evaluate.tools.CustomDialog;
import com.soonfor.evaluate.tools.ImageUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AppDialog;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.dialog.normal.NormalDialog;
import com.soonfor.evaluate.tools.dialog.normal.OnBtnClickL;
import com.soonfor.systemcodes.SystemCodes;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SendRegisterActivity extends BaseActivity implements AddPhotosView.EventListener, AbnormalDeclareView.CallBack {

	private Activity mActivity;
	@BindView(R.id.measure_title)
	TextView tv_title;
	@BindView(R.id.result_build_name)
	TextView tv_client;
	@BindView(R.id.result_build_date_real)
	TextView tv_actual_time;
	private String dlvid;
	@BindView(R.id.build_input_remark)
	EditText et_input_remark;

	private RequestParams savaParams;
	private View rootView;
	@BindView(R.id.viewAbnormalDeclare)
	AbnormalDeclareView viewAbnormalDeclare;//异常申报View
	//签收，现场及异常图片选择
	@BindView(R.id.view_sigining)
	AddPhotosView view_photos_sigin;
	//现场异常图片
	@BindView(R.id.view_xc_yj)
	AddPhotosView view_photos_scene_abnormal;
	/*删除的时候用到*/
	AddPhotosView operatePhotoView;
	int deletePosition = -1;//删除时候的位置
	/*送货视频*/
	@BindView(R.id.view_send_video)
	AddVideoView view_send_video;

	B21SendDetail sendDetail;

	private int CODE_SIGIN = 1000,CODE_SCENE_ABNORMAL = 2000;
	private int CODE_VIDEO = 3001;
	private int CODE_DELETE_IMG = 4001;//删除图片
	private int CODE_DELETE_VIDEO = 4002;//删除视频
	private boolean siginUploadFn = false, sceneAbnUploadFn = false,viedeoUpload = false;
	private ArrayList<String> siginPaths = new ArrayList<String>();//已上传成功的签收图片
	private ArrayList<String> sceneAbnPaths = new ArrayList<String>();//已上传成功的现场及异常图片
	private ArrayList<BeanImage> videoPaths = new ArrayList<BeanImage>();//已上传成功的现场及异常图片

	private int pageType = 0;//页面用途 0-送货完工登记 1-仅上传图片和录音，不完工登记


	@Override
	protected void init() {
		mActivity = SendRegisterActivity.this;
		Intent nIntent = getIntent();
		dlvid = nIntent.getStringExtra("dlvid");
		pageType = nIntent.getIntExtra("pageType", 0);
		RequestParams params = new RequestParams();
		params.addBodyParameter("sf_action", "dlvgettaskdetail");
		params.addBodyParameter("usercode", MyApplication.getUserCode());
		params.addBodyParameter("dlvid", dlvid);
		connect(params, NetManager.SEND_CONTENT);
	}

	@Override
	protected void initView() {
		rootView = View.inflate(this, R.layout.activity_result_build, null);
		setContentView(rootView);

		ButterKnife.bind(this);

		if (pageType==1) {
			tv_title.setText("送货确认-上传图片");
		}else {
			tv_title.setText("送货完工登记");
		}
		tv_actual_time.setText(TimeUtils.formatTime(System.currentTimeMillis(), ""));
		initAll();
	}

	public void initAll() {
		view_photos_sigin.initView(mActivity, CODE_SIGIN, this);
		view_photos_sigin.initData("客户签收单拍照", 99);
		view_photos_sigin.setAddMediaListenner(mediaListenner);
		view_photos_scene_abnormal.initView(mActivity,CODE_SCENE_ABNORMAL, this);
		view_photos_scene_abnormal.initData("现场及异常拍照", 99);
		view_photos_scene_abnormal.setAddMediaListenner(mediaListenner);
		view_send_video.setVideoViewListenner(videoViewListenner);
		view_send_video.initView(mActivity,CODE_VIDEO,this);
		view_send_video.initData("送货视频",99);
		et_input_remark.setVisibility(View.VISIBLE);
		if(pageType == 1) {
			viewAbnormalDeclare.setVisibility(View.GONE);
		}else {
			viewAbnormalDeclare.setVisibility(View.VISIBLE);
			viewAbnormalDeclare.initAView(mActivity, "是否产生售后投诉单", this, 0);
		}
	}

	public void showPicker(View view) {
		AppDialog.createPicker(this, tv_actual_time).show();
	}


	/*删除视频*/
	AddVideoView.AddVideoViewListenner videoViewListenner = new AddVideoView.AddVideoViewListenner() {
		@Override
		public void onDeleteVideo(AddVideoView view,final LocalMedia media,final int position) {
			CustomDialog.getCanDismissDialog(SendRegisterActivity.this, "温馨提示", "此视频存在服务器，确定要删除该视频吗？", new OnBtnClickL() {
				@Override
				public void onBtnClick(View view) {
					deletePosition = position;
					RequestParams requestParams = new RequestParams();
					requestParams.addBodyParameter("sf_action","istdelimg");
					requestParams.addBodyParameter("usercode",MyApplication.getUserCode());
					requestParams.addBodyParameter("dlvid",dlvid);
					requestParams.addBodyParameter("dlvimgitemid",getDeleteImageId(media.getPath()));
					connect(requestParams,CODE_DELETE_VIDEO);
				}
			});
		}
	};

	/*获取媒体文件的id*/
	String getDeleteImageId(String path){
		String decodePath = "";
		try {
			decodePath = URLDecoder.decode(path,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String imgId = "";
		for (B21SendDetail.BuildIMG buildIMG : sendDetail.data.imgitem){
			if (decodePath.endsWith(buildIMG.imgpath)){
				imgId = buildIMG.dlvimgitemid;
				break;
			}
		}
		return imgId;
	}

	/*点击删除监听*/
	AddPhotosView.AddMediaListenner mediaListenner = new AddPhotosView.AddMediaListenner() {
		@Override
		public void onDelete(final AddPhotosView pohoview,final LocalMedia media,final int position) {
			CustomDialog.getCanDismissDialog(SendRegisterActivity.this, "温馨提示", "此图片存在服务器，确定要删除该图片吗？", new OnBtnClickL() {
				@Override
				public void onBtnClick(View view) {
					deletePosition = position;
					operatePhotoView = pohoview;

					RequestParams requestParams = new RequestParams();
					requestParams.addBodyParameter("sf_action","istdelimg");
					requestParams.addBodyParameter("usercode",MyApplication.getUserCode());
					requestParams.addBodyParameter("dlvid",dlvid);
					requestParams.addBodyParameter("dlvimgitemid",getDeleteImageId(media.getPath()));
					connect(requestParams,CODE_DELETE_IMG);

				}
			});
		}
	};


	@Override
	protected void onActivityResult(int request, int result, Intent data) {
		super.onActivityResult(request, result, data);
		if (result != RESULT_OK) {
			return;
		}
		if (request == AbnormalDeclareView.REQUEST_CODE_CHOISE_AB_TYPE) {//选中异常申报类型后
			if(data != null) {
				OrderAttributeBean checkedBean = data.getParcelableExtra(AbnormalDeclareView.BIND_DATA);
				viewAbnormalDeclare.setAbTypeText(checkedBean.getAttId(), checkedBean.getAttName());
			}
		}else {
			if (Math.abs(request - CODE_SIGIN) < 4) {//客户签收
				view_photos_sigin.onActivityResult(request, data);
			}else if (Math.abs(request -CODE_SCENE_ABNORMAL) < 4){//现场异常
				view_photos_scene_abnormal.onActivityResult(request, data);
			}else if(request == CODE_VIDEO + 1 ){
				view_send_video.onActivityResult(request,data);
			}
		}
	}


	//获取异常类型
	@Override
	public void getAbnormalType() {
		RequestParams rqTypes = new RequestParams();
		rqTypes.addBodyParameter("sf_action", "getabnormaltype");
		rqTypes.addBodyParameter("usercode", MyApplication.getUserCode());

		showDialog("请求异常类型...", true);
		connect(rqTypes, NetManager.BUILD_ABN_TYPES);
	}

	//打开图库
	@Override
	public void openAlbum(int id) {
		// 当达到最高图片数量时直接返回
		if (isOutOfLimit(id))
			return;
		List<LocalMedia> lastMedias = new ArrayList<>();
		if (id == CODE_SIGIN) {
			lastMedias.addAll(view_photos_sigin.getFileList());
		}else if (id ==CODE_SCENE_ABNORMAL) {
			lastMedias.addAll(view_photos_scene_abnormal.getFileList());
		}
		ImageUtils.pictureSelect(mActivity, PictureConfig.MULTIPLE, 99, lastMedias, id + 1);
	}
	//打开相机拍照
	@Override
	public boolean openCamera(int id) {
        // 当达到最高图片数量时直接返回
		return isOutOfLimit(id);
//		if (isOutOfLimit(id))
//			return;
//		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//		startActivityForResult(intent, id + 2);
	}


	@Override
	public void showLoadDialog() {
		showDialog("上传图片中...", false);
	}

	@Override
	public void closeLoadDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}
	/**
	 * 判断容器里的图片是否达到最高选择数量
	 */
	private boolean isOutOfLimit(int code) {
		// 下面开始判断整体容器里的图片是否达到最高选择数量
		if (code == CODE_SIGIN) {
			if (view_photos_sigin.getPhotosCount() >= 99) {
				Toast.show(this, "客户签收单图片最多上传99张", 2000);
				return true;
			}
		}else if (code == CODE_SCENE_ABNORMAL) {
			if (view_photos_scene_abnormal.getPhotosCount() >= 99) {
				Toast.show(this, "现场及现场及异常图片最多上传99张", 2000);
				return true;
			}
		}
		return false;
	}


	//提交
	public void save(View view) {
		String ridate = tv_actual_time.getText().toString().trim();
		String ctsNeed = et_input_remark.getText().toString();
		if (TextUtils.isEmpty(ridate)) {
			Toast.show(mActivity, "实际送货时间不能为空", 2000);
			return;
		}
		if (view_photos_sigin.getPhotosCount()==0 || view_photos_scene_abnormal.getPhotosCount()==0) {
			Toast.show(mActivity, "请至少上传一张图片", 2000);
			return;
		}
		if (SystemCodes.getInstance().getDSM_IstFinishMustVideo() == 1 && view_send_video.getPhotosCount() == 0){
			Toast.show(mActivity, "请至少上传一个视频", 2000);
			return;
		}
		/*送货完工时*/
		if (SystemCodes.getInstance().getDSM_FinishMustRemark() == 1 && TextUtils.isEmpty(ctsNeed) && pageType == 0){
			Toast.show(mActivity, "请输入现场及异常情况", 2000);
			return;
		}
		savaParams = new RequestParams();
		savaParams.addBodyParameter("sf_action", "dlvfinish");
		savaParams.addBodyParameter("usercode", MyApplication.getUserCode());
		savaParams.addBodyParameter("dlvid", dlvid);
		savaParams.addBodyParameter("rddate", ridate);
		savaParams.addBodyParameter("dlvremark", ctsNeed);
		if(viewAbnormalDeclare != null && viewAbnormalDeclare.resultBean != null) {
			AbnormalDeclareView.ResultBean resultBean = viewAbnormalDeclare.getDatas();
			if(resultBean.getIfGenAdOrder() == 1 && resultBean.getAbnormalDesc().equals("")) {
				Toast.show(mActivity, "异常描述不能为空", 2000);
				return;
			}
			savaParams.addBodyParameter("fifgenabnbill", resultBean.getIfGenAdOrder()+"");
			savaParams.addBodyParameter("fabnormaltype", resultBean.getTypeCode());
			savaParams.addBodyParameter("fabnremark", resultBean.getAbnormalDesc());
		}
		initUpload();
		// 上传客户签收的图片
		view_photos_sigin.postPics();
		// 上传现场及异常的图片
		view_photos_scene_abnormal.postPics();
		/*
		* 上传送货视频
		* */
		view_send_video.postPics();
	}
	private void initUpload() {
		showDialog("提交数据中...", false);
		if (siginPaths == null) siginPaths = new ArrayList<>();
		else siginPaths.clear();
		siginUploadFn = false;
		if (sceneAbnPaths == null) sceneAbnPaths = new ArrayList<>();
		else sceneAbnPaths.clear();
		sceneAbnUploadFn = false;
		if (videoPaths == null) videoPaths = new ArrayList<>();
		else videoPaths.clear();
		viedeoUpload = false;
	}

	//上传单张图片
	@Override
	public void uploadPic(RequestParams params, int requestCode) {
		updateIMG(params, requestCode);
	}

	@Override
	public void uploadVideoByParam(RequestParams params, int code) {
		uploadVideo(params, code);
	}

	@Override
	public void afterUploadVideos(boolean isSuccess, ArrayList<BeanImage> urls, int requestCode) {
		viedeoUpload = true;
		videoPaths = urls;
		buildJson();
	}

	//所有图片上传成功
	@Override
	public void afterUploadPics(boolean isSuccess, ArrayList<String> urls, int _id) {
		if (isSuccess) {
			if (_id == CODE_SIGIN) {
				siginUploadFn = true;
				siginPaths = urls;
			} else if (_id == CODE_SCENE_ABNORMAL){
				sceneAbnUploadFn = true;
				sceneAbnPaths = urls;
			}
			buildJson();
		}else {
			closeLoadDialog();
		}
	}

	// 组建json提交服务器
	private void buildJson() {
		if (siginUploadFn && sceneAbnUploadFn && viedeoUpload) {
			buildIMGJson();
			connect(savaParams, NetManager.BUILD_RESULT);
		}
	}

	private void buildIMGJson() {
		try {
			JSONArray jsonArrALL = new JSONArray();
			for (int i = 0; i < siginPaths.size(); i++) {
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("measureid", dlvid);
				jsonObj.put("imgpath", siginPaths.get(i));
				jsonObj.put("phaselv", "5");
				jsonArrALL.put(jsonObj);
			}
			for (int i = 0; i < sceneAbnPaths.size(); i++) {
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("measureid", dlvid);
				jsonObj.put("imgpath", sceneAbnPaths.get(i));
				jsonObj.put("phaselv", "6");
				jsonArrALL.put(jsonObj);
			}
			for (BeanImage beanImage : videoPaths){
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("measureid", dlvid);
				jsonObj.put("videoimgpath", beanImage.filepath);
				jsonObj.put("imgpath", beanImage.videoimgpath);
				jsonObj.put("filetype","3");
				jsonObj.put("phaselv", "6");
				jsonArrALL.put(jsonObj);
			}

			savaParams.addBodyParameter("imgitem", jsonArrALL.toString());
			if (pageType == 1) {
				//仅上传图片和录音，不完工登记
				savaParams.addBodyParameter("fifupfinflag", "0");
			}
			// Log.i("JSON", "imgitem = " + jsonArrALL.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	//上传图片的回调
	@Override
	protected void onNetIMGSuccess(int code, String result) {
		if (code == CODE_SIGIN) view_photos_sigin.uploadSuccess(code, result);
		else if (code == CODE_SCENE_ABNORMAL) view_photos_scene_abnormal.uploadSuccess(code, result);
		else if (code == CODE_VIDEO) view_send_video.uploadSuccess(code,result);
	}
	@Override
	protected void onNetErorr(int code, String msg) {
		super.onNetErorr(code, msg);
		if (code == CODE_SIGIN) view_photos_sigin.uploadFail(code, msg);
		else if (code == CODE_SCENE_ABNORMAL) view_photos_scene_abnormal.uploadFail(code, msg);
		else if (NetManager.BUILD_RESULT == code) {
			clearUpdateData();closeLoadDialog();
		}else if (code == CODE_VIDEO){
			view_send_video.uploadFail(code,msg);
		}else if (code == CODE_DELETE_IMG){
			Toast.show(mActivity,msg,Toast.LENGTH_LONG);
		}else if (code == CODE_DELETE_VIDEO){
			Toast.show(mActivity,msg,Toast.LENGTH_LONG);
		}
	}


	//非上传图片的请求成功回调
	@Override
	protected void onNetSuccess(int code, String result) {
		if (NetManager.SEND_CONTENT == code) {
			super.onNetSuccess(code, result);
			B21SendDetail bean = gson.fromJson(result, B21SendDetail.class);
			// 进入activity时获取的同事信息
			if (bean.success) {
				sendDetail = bean;
				if (TextUtils.isEmpty(bean.data.buildname)) {
					tv_client.setText(bean.data.cstname);
				} else {
					tv_client.setText(bean.data.buildname + "-"
							+ bean.data.cstname);
				}
				List<LocalMedia> sinArr = new ArrayList<>();
				List<LocalMedia> sceneArr = new ArrayList<>();
				List<LocalMedia> videoImgArr = new ArrayList<>();
				for (B21SendDetail.BuildIMG buildIMG : bean.data.imgitem){
					LocalMedia media = new LocalMedia();
					String component = "";
					String videoimgpath = "";
					try {
						component = TextUtils.isEmpty(buildIMG.imgpath)?"":URLEncoder.encode(buildIMG.imgpath, "UTF-8");
						videoimgpath = TextUtils.isEmpty(buildIMG.videoimgpath)?"":URLDecoder.decode(buildIMG.videoimgpath,"UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					String url = NetManager.getDownloadURL() + "?filepath=" + component;
					media.setPath(url);
					if (!TextUtils.isEmpty(videoimgpath)){//视频缩略图房子啊压缩图路径中
						videoimgpath = NetManager.getDownloadURL() + "?filepath=" + videoimgpath;
						media.setCompressPath(videoimgpath);
					}else {
						media.setCompressPath(url);
					}
					media.setMimeType(PictureMimeType.ofJPEG());
					if (buildIMG.phaselv == 5){
						sinArr.add(media);
					}else if (buildIMG.phaselv == 6){
						if (buildIMG.filetype == 3){
							media.setCompressPath(url);
							media.setPath(videoimgpath);
							videoImgArr.add(media);
						}else {
							sceneArr.add(media);
						}
					}
				}
				view_photos_sigin.setImagesList(sinArr);
				view_photos_scene_abnormal.setImagesList(sceneArr);
				view_send_video.setVideoList(videoImgArr);
			}
		}

		if (NetManager.BUILD_RESULT == code) {
			super.onNetSuccess(code, result);
			B12Measure designer = gson.fromJson(result, B12Measure.class);
			// 进入activity时获取的同事信息
			if (designer.success) {
				Toast.show(this, "提交成功", 2000);
				setResult(SendActivity.REFLESH_DATA);
				finish();// designer.msg
			} else {
				Toast.show(this, "提交失败 = " + designer.msg, 2000);
				Log.i("JSON", "提交失败 = " + designer.msg);
			}closeLoadDialog();
		}else if (NetManager.BUILD_ABN_TYPES == code) {
			AbnormalType aType = null;
			try{
				aType = gson.fromJson(result, AbnormalType.class);
			}catch (Exception e){}
			if(aType != null) {
				viewAbnormalDeclare.showListDialog(1, aType.data);
			}
		}else if (CODE_DELETE_IMG == code){//删除图片

			BeanBase beanBase = gson.fromJson(result,BeanBase.class);
			if (beanBase.success){
				if (operatePhotoView != null){
					operatePhotoView.removeItem(deletePosition);
					operatePhotoView = null;
					deletePosition = -1;
				}
			}else {
				Toast.show(mActivity,beanBase.msg,Toast.LENGTH_LONG);
			}
		}else if (CODE_DELETE_VIDEO == code){
			BeanBase beanBase = gson.fromJson(result,BeanBase.class);
			if (beanBase.success){
				view_send_video.removeItem(deletePosition);
				deletePosition = -1;
			}else {
				Toast.show(mActivity,beanBase.msg,Toast.LENGTH_LONG);
			}
		}
	}
	private void clearUpdateData() {
		savaParams = null;
	}

}
